'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { 
  ArrowLeft, 
  User, 
  Phone, 
  MapPin, 
  Calendar, 
  Activity, 
  Heart, 
  Zap, 
  TrendingUp,
  Clock,
  Database,
  Filter,
  Moon,
  Ruler,
  Weight
} from 'lucide-react'
import ReactECharts from 'echarts-for-react'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { HeartRateChart } from './heart-rate-echart'
import { StepChart } from './step-chart'
import { HRVChart } from './hrv-chart'
import { TemperatureChart } from './temperature-chart'
import { ActivityAnalysisChart } from './activity-analysis-chart'
import { EnergyConsumptionChart } from './energy-consumption-chart'

interface UserDetail {
  id: number
  mobile: string
  cc: number
  name: string
  avatar?: string
  gender: number
  age: number
  height: string
  weight: string
  city: string
  createTime: string
  lastActiveTime: string
  totalHealthLogs: number
  recentHealthLogs: any[]
  healthStats: { type: string; count: number }[]
}

interface UserDetailInlineProps {
  userId: number
  onBack: () => void
}

export function UserDetailInline({ userId, onBack }: UserDetailInlineProps) {
  const [userDetail, setUserDetail] = useState<UserDetail | null>(null)
  const [loading, setLoading] = useState(true)
  const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0])
  const [selectedDataType, setSelectedDataType] = useState('sleep')
  const [sleepChartData, setSleepChartData] = useState<any[]>([])
  const [heartRateChartData, setHeartRateChartData] = useState<any[]>([])
  const [restingHeartRateData, setRestingHeartRateData] = useState<any[]>([])
  const [chartOption, setChartOption] = useState<any>(null)
  const [chartLoading, setChartLoading] = useState(false)

  useEffect(() => {
    fetchUserDetail()
  }, [userId])

  // 监听日期和数据类型变化，重新获取图表数据
  useEffect(() => {
    if (userDetail) {
      if (selectedDataType === 'sleep') {
        fetchSleepData()
      } else if (selectedDataType === 'heart_rate') {
        fetchHeartRateData()
      } else if (selectedDataType === 'resting_heart_rate') {
        fetchRestingHeartRateData()
      }
    }
  }, [userDetail, selectedDate, selectedDataType])

  const fetchUserDetail = async () => {
    setLoading(true)
    try {
      const response = await fetch(`/api/users/${userId}`)
      const result = await response.json()
      
      if (result.success) {
        setUserDetail(result.data)
      } else {
        console.error('获取用户详情失败:', result.message)
      }
    } catch (error) {
      console.error('获取用户详情错误:', error)
    } finally {
      setLoading(false)
    }
  }

  const fetchSleepData = async () => {
    if (!userDetail?.mobile) return
    
    setChartLoading(true)
    try {
      // 计算睡眠周期：选择日期的前一天18:00到当天18:00
      const targetDate = new Date(selectedDate)
      const startTime = new Date(targetDate)
      startTime.setDate(startTime.getDate() - 1)
      startTime.setHours(18, 0, 0, 0)
      
      const endTime = new Date(targetDate)
      endTime.setHours(18, 0, 0, 0)
      
      // 在API请求中包含日期范围参数
      const params = new URLSearchParams({
        mobile: userDetail.mobile,
        type: 'sleep',
        page: '1',
        limit: '100',
        start_date: selectedDate, // 添加选择的日期
        start_time: Math.floor(startTime.getTime() / 1000).toString(), // 开始时间戳（秒）
        end_time: Math.floor(endTime.getTime() / 1000).toString() // 结束时间戳（秒）
      })
      
      const response = await fetch(`/api/health/query?${params}`)
      const result = await response.json()
      
      if (result.success && result.data.logs.length > 0) {
        // 由于API已经按时间范围筛选，直接处理返回的数据
        processSleepChartData(result.data.logs, startTime, endTime)
      } else {
        setSleepChartData([])
      }
    } catch (error) {
      console.error('获取睡眠数据错误:', error)
      setSleepChartData([])
    } finally {
      setChartLoading(false)
    }
  }

  const processSleepChartData = (logs: any[], startTime: Date, endTime: Date) => {

    
    // 收集所有睡眠片段，精确计算时间
    const sleepSegments: Array<{
      type: string
      startTime: number
      endTime: number
      startHour: number
      endHour: number
      duration: number
      qualityValue: number
    }> = []
    
    // 处理睡眠数据
    logs.forEach((log, logIndex) => {
      try {
        const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
        
        if (logData.arraySleepQuality && Array.isArray(logData.arraySleepQuality)) {
          const sleepData = logData.arraySleepQuality
          const unitLength = parseInt(logData.sleepUnitLength || '1')
          // 使用startTs作为起始时间，确保是毫秒时间戳
          let logStartTime = parseInt(logData.startTs || log.timestamp)
          // 如果是秒时间戳，转换为毫秒
          if (logStartTime < 10000000000) {
            logStartTime = logStartTime * 1000
          }
          

          
          // 连续相同质量的睡眠片段合并
          let currentSegment: any = null
          
          sleepData.forEach((quality: any, index: number) => {
            const qualityNum = typeof quality === 'string' ? parseInt(quality) : quality
            // 正确计算时间：从startTs开始，每个数据点代表unitLength分钟
            const dataStartTime = logStartTime + (index * unitLength * 60 * 1000)
            const dataEndTime = logStartTime + ((index + 1) * unitLength * 60 * 1000)
            
            // 修正睡眠类型映射
            let sleepType = ''
            switch (qualityNum) {
              case 1: sleepType = '深度睡眠'; break
              case 2: sleepType = '浅睡眠'; break
              case 3: sleepType = 'REM睡眠'; break
              case 4: sleepType = '浅睡眠'; break // 有些数据用4表示浅睡眠
              case 5: sleepType = '清醒'; break
              case 11: sleepType = '深度睡眠'; break // 添加对质量值11的支持
              default: 
                console.log(`未知睡眠质量值: ${qualityNum}`)
                sleepType = '未知'
                break
            }
            
            // 跳过未知类型
            if (sleepType === '未知') return
            
            if (currentSegment && currentSegment.type === sleepType) {
              // 延长当前片段
              currentSegment.endTime = dataEndTime
              currentSegment.duration += unitLength
            } else {
              // 保存上一个片段
              if (currentSegment) {
                // 计算相对于睡眠周期开始时间的小时数
                const segmentStartHour = (currentSegment.startTime - startTime.getTime()) / (60 * 60 * 1000)
                const segmentEndHour = (currentSegment.endTime - startTime.getTime()) / (60 * 60 * 1000)
                
                currentSegment.startHour = segmentStartHour
                currentSegment.endHour = segmentEndHour
                
                sleepSegments.push(currentSegment)

              }
              // 开始新片段
              currentSegment = {
                type: sleepType,
                startTime: dataStartTime,
                endTime: dataEndTime,
                duration: unitLength,
                startHour: 0,
                endHour: 0,
                qualityValue: qualityNum
              }
            }
          })
          
          // 保存最后一个片段
          if (currentSegment) {
            const segmentStartHour = (currentSegment.startTime - startTime.getTime()) / (60 * 60 * 1000)
            const segmentEndHour = (currentSegment.endTime - startTime.getTime()) / (60 * 60 * 1000)
            
            currentSegment.startHour = segmentStartHour
            currentSegment.endHour = segmentEndHour
            
            sleepSegments.push(currentSegment)

          }
        }
      } catch (e) {
        console.error('处理睡眠数据错误:', e, log)
      }
    })
    
    // 按时间排序片段
    sleepSegments.sort((a, b) => a.startTime - b.startTime)
    

    setSleepChartData(sleepSegments)
    
    // 生成ECharts配置
    generateEChartsOption(sleepSegments, startTime, endTime)
  }

  const generateEChartsOption = (segments: any[], startTime: Date, endTime: Date) => {
    // 睡眠类型映射
    const sleepTypeMap = {
      '深度睡眠': { value: 0, color: '#1e40af' },
      '浅睡眠': { value: 1, color: '#3b82f6' },
      'REM睡眠': { value: 2, color: '#8b5cf6' },
      '清醒': { value: 3, color: '#ef4444' }
    }

    // 转换数据为ECharts格式
    const seriesData = segments.map((segment) => {
      const typeInfo = sleepTypeMap[segment.type as keyof typeof sleepTypeMap]
      if (!typeInfo) {
        return {
          name: segment.type,
          value: [
            0, // 默认位置
            new Date(segment.startTime).getTime(),
            new Date(segment.endTime).getTime(),
            segment.duration
          ],
          itemStyle: {
            color: '#6b7280' // 默认灰色
          }
        }
      }
      
      return {
        name: segment.type,
        value: [
          typeInfo.value,
          new Date(segment.startTime).getTime(),
          new Date(segment.endTime).getTime(),
          segment.duration
        ],
        itemStyle: {
          color: typeInfo.color
        }
      }
    })

    // 动态计算时间轴范围
    let actualStartTime = startTime.getTime()
    let actualEndTime = endTime.getTime()
    
    if (segments.length > 0) {
      // 找到实际睡眠数据的最早和最晚时间
      const dataStartTime = Math.min(...segments.map(seg => seg.startTime))
      const dataEndTime = Math.max(...segments.map(seg => seg.endTime))
      
      // 向下取整到最近的偶数小时（例如23:01 -> 22:00, 22:30 -> 22:00）
      const startDate = new Date(dataStartTime)
      let startHour = startDate.getHours()
      // 如果不是偶数小时，或者有分钟/秒，则向下取整到偶数小时
      if (startHour % 2 !== 0 || startDate.getMinutes() > 0 || startDate.getSeconds() > 0) {
        startHour = Math.floor(startHour / 2) * 2
      }
      const chartStartTime = new Date(startDate)
      chartStartTime.setHours(startHour, 0, 0, 0)
      
      // 向上取整到最近的偶数小时（例如7:03 -> 8:00, 7:00 -> 8:00）
      const endDate = new Date(dataEndTime)
      let endHour = endDate.getHours()
      // 如果不是偶数小时，或者有分钟/秒，则向上取整到偶数小时
      if (endHour % 2 !== 0 || endDate.getMinutes() > 0 || endDate.getSeconds() > 0) {
        endHour = Math.ceil((endHour + 1) / 2) * 2
      } else {
        // 如果正好是偶数小时且无分钟秒，也要向上取整一个偶数小时
        endHour = endHour + 2
      }
      const chartEndTime = new Date(endDate)
      chartEndTime.setHours(endHour, 0, 0, 0)
      
      actualStartTime = chartStartTime.getTime()
      actualEndTime = chartEndTime.getTime()
      

    }

    const option = {
      title: {
        text: '睡眠质量分析',
        left: 'center',
        textStyle: {
          fontSize: 16,
          color: '#374151'
        }
      },
      tooltip: {
        formatter: (params: any) => {
          const data = params.data
          const startTime = new Date(data.value[1])
          const endTime = new Date(data.value[2])
          const duration = data.value[3]
          return `
            <div>
              <strong>${data.name}</strong><br/>
              开始时间: ${startTime.toLocaleTimeString()}<br/>
              结束时间: ${endTime.toLocaleTimeString()}<br/>
              持续时间: ${duration}分钟
            </div>
          `
        }
      },
      grid: {
        left: '10%',
        right: '10%',
        top: '15%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'time',
        min: actualStartTime,
        max: actualEndTime,
        axisLabel: {
          formatter: (value: number) => {
            const date = new Date(value)
            return `${date.getHours().toString().padStart(2, '0')}:00`
          },
          interval: 2 * 60 * 60 * 1000 // 2小时间隔
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#e5e7eb',
            type: 'dashed'
          }
        }
      },
      yAxis: {
        type: 'category',
        data: ['深度睡眠', '浅睡眠', 'REM睡眠', '清醒'],
        axisLabel: {
          fontSize: 12,
          color: '#6b7280'
        },
        axisTick: {
          show: false
        },
        axisLine: {
          show: false
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#f3f4f6',
            width: 1
          }
        },
        // 保持类别间距，确保每个类别有独立的区间
        boundaryGap: true
      },
      series: [{
        type: 'custom',
        renderItem: (params: any, api: any) => {
          const categoryIndex = api.value(0)
          const start = api.coord([api.value(1), categoryIndex])
          const end = api.coord([api.value(2), categoryIndex])
          
          // 获取单个类别的高度
          const categoryHeight = api.size([0, 1])[1]
          // 条形图高度占类别高度的80%，留20%作为间距
          const barHeight = categoryHeight * 0.8
          
          // 计算Y轴位置：条形图应该在类别的中心位置
          const categoryCenter = start[1]
          const barY = categoryCenter - barHeight / 2
          
          // 从数据项中获取颜色
          const dataItem = seriesData[params.dataIndex]
          const color = dataItem?.itemStyle?.color || '#6b7280'
          

          
          return {
            type: 'rect',
            shape: {
              x: start[0],
              y: barY,
              width: Math.max(2, end[0] - start[0]), // 确保最小宽度
              height: barHeight
            },
            style: {
              fill: color,
              stroke: '#ffffff',
              lineWidth: 1
            }
          }
        },
        data: seriesData
      }]
    }

    setChartOption(option)
  }

  const fetchHeartRateData = async () => {
    if (!userDetail?.mobile) return
    
    setChartLoading(true)
    try {
      // 计算当天的时间范围：00:00-24:00
      const targetDate = new Date(selectedDate)
      const startTime = new Date(targetDate)
      startTime.setHours(0, 0, 0, 0)
      
      const endTime = new Date(targetDate)
      endTime.setHours(23, 59, 59, 999)
      
      const params = new URLSearchParams({
        mobile: userDetail.mobile,
        type: 'heart_rate',
        page: '1',
        limit: '1000', // 获取更多数据用于聚合
        start_date: selectedDate,
        start_time: Math.floor(startTime.getTime() / 1000).toString(),
        end_time: Math.floor(endTime.getTime() / 1000).toString()
      })
      
      const response = await fetch(`/api/health/query?${params}`)
      const result = await response.json()
      
      if (result.success && result.data.logs.length > 0) {
        processHeartRateChartData(result.data.logs, startTime, endTime)
      } else {
        setHeartRateChartData([])
        setChartOption(null)
      }
    } catch (error) {
      console.error('获取心率数据错误:', error)
      setHeartRateChartData([])
      setChartOption(null)
    } finally {
      setChartLoading(false)
    }
  }

  const processHeartRateChartData = (logs: any[], startTime: Date, endTime: Date) => {
    // 解析心率数据
    const heartRatePoints: Array<{
      timestamp: number
      value: number
      isAutoMeasure: boolean
    }> = []
    
    logs.forEach((log) => {
      try {
        const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
        
        if (logData.onceHeartValue) {
          const heartRate = parseInt(logData.onceHeartValue)
          const timestamp = parseInt(logData.ts || log.timestamp)
          
          // 确保是毫秒时间戳
          const finalTimestamp = timestamp < 10000000000 ? timestamp * 1000 : timestamp
          
          if (!isNaN(heartRate) && heartRate > 0) {
            heartRatePoints.push({
              timestamp: finalTimestamp,
              value: heartRate,
              isAutoMeasure: logData.isAutoMeasure !== undefined ? !logData.isAutoMeasure : true // false=自动测量, true=手动测量
            })
          }
        }
      } catch (e) {
        console.error('处理心率数据错误:', e, log)
      }
    })
    
    // 按时间排序
    heartRatePoints.sort((a, b) => a.timestamp - b.timestamp)
    
    // 按小时聚合数据
    const hourlyData: Array<{
      hour: number
      min: number
      max: number
      count: number
      autoCount: number
      manualCount: number
    }> = []
    
    // 初始化24小时的数据结构
    for (let hour = 0; hour < 24; hour++) {
      hourlyData[hour] = {
        hour,
        min: Infinity,
        max: -Infinity,
        count: 0,
        autoCount: 0,
        manualCount: 0
      }
    }
    
    // 聚合数据到对应小时
    heartRatePoints.forEach((point) => {
      const date = new Date(point.timestamp)
      const hour = date.getHours()
      
      if (hour >= 0 && hour < 24) {
        const hourData = hourlyData[hour]
        
        if (point.value < hourData.min) hourData.min = point.value
        if (point.value > hourData.max) hourData.max = point.value
        hourData.count++
        
        if (point.isAutoMeasure) {
          hourData.manualCount++ // isAutoMeasure=true 表示手动测量
        } else {
          hourData.autoCount++ // isAutoMeasure=false 表示自动测量
        }
      }
    })
    
    // 过滤掉没有数据的小时，并修正无效的min/max值
    const validHourlyData = hourlyData
      .filter(data => data.count > 0)
      .map(data => ({
        ...data,
        min: data.min === Infinity ? 0 : data.min,
        max: data.max === -Infinity ? 0 : data.max
      }))
    
    setHeartRateChartData(validHourlyData)
    generateHeartRateEChartsOption(validHourlyData, startTime, endTime)
  }

  const generateHeartRateEChartsOption = (hourlyData: any[], startTime: Date, endTime: Date) => {
    // 生成完整的24小时时间轴，确保与数据对应
    const timeLabels = []
    const categoryData = []
    
    // 创建24小时的完整数据结构
    for (let hour = 0; hour < 24; hour++) {
      categoryData.push(hour)
      if (hour % 2 === 0) {
        timeLabels.push(`${hour.toString().padStart(2, '0')}:00`)
      }
    }
    
    // 计算实际数据的最小值和最大值
    let globalMin = Infinity
    let globalMax = -Infinity
    
    hourlyData.forEach((data) => {
      if (data.min < globalMin) globalMin = data.min
      if (data.max > globalMax) globalMax = data.max
    })
    
    // 如果没有数据，设置默认范围
    if (globalMin === Infinity || globalMax === -Infinity) {
      globalMin = 60
      globalMax = 100
    }
    
    // 为Y轴范围添加一些缓冲区，让图表更美观
    const range = globalMax - globalMin
    const buffer = Math.max(5, Math.ceil(range * 0.1)) // 至少5的缓冲区，或者10%的范围
    const yAxisMin = Math.max(0, globalMin - buffer)
    const yAxisMax = globalMax + buffer
    
    // 转换数据为ECharts格式，确保每个小时都有对应的位置
    const seriesData: any[] = []
    
    // 为每个有数据的小时创建数据点
    hourlyData.forEach((data) => {
      seriesData.push({
        name: `${data.hour}:00`,
        value: [
          data.hour, // X轴位置（小时，0-23）
          data.min,  // 最小值
          data.max,  // 最大值
          data.count, // 数据点数量
          data.autoCount, // 自动测量数量
          data.manualCount // 手动测量数量
        ],
        itemStyle: {
          color: '#ef4444' // 红色
        }
      })
    })

    const option = {
      title: {
        text: '心率数据分析',
        left: 'center',
        textStyle: {
          fontSize: 16,
          color: '#374151'
        }
      },
      tooltip: {
        formatter: (params: any) => {
          const data = params.data
          const hour = data.value[0]
          const min = data.value[1]
          const max = data.value[2]
          const count = data.value[3]
          const autoCount = data.value[4]
          const manualCount = data.value[5]
          
          return `
            <div>
              <strong>${hour.toString().padStart(2, '0')}:00 - ${(hour + 1).toString().padStart(2, '0')}:00</strong><br/>
              心率范围: ${min} - ${max} 次/分<br/>
              测量次数: ${count}次<br/>
              自动测量: ${autoCount}次<br/>
              手动测量: ${manualCount}次
            </div>
          `
        }
      },
      grid: {
        left: '10%',
        right: '10%',
        top: '15%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: categoryData, // 使用0-23的数字数组
        axisLabel: {
          fontSize: 12,
          color: '#6b7280',
          formatter: (value: number) => {
            // 只显示偶数小时的标签
            if (value % 2 === 0) {
              return `${value.toString().padStart(2, '0')}:00`
            }
            return ''
          },
          interval: 0 // 显示所有刻度，但只有偶数小时有标签
        },
        axisTick: {
          show: true,
          alignWithLabel: true
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#e5e7eb'
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#f3f4f6',
            type: 'dashed'
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '心率 (次/分)',
        min: yAxisMin,
        max: yAxisMax,
        nameTextStyle: {
          color: '#6b7280',
          fontSize: 12
        },
        axisLabel: {
          fontSize: 12,
          color: '#6b7280'
        },
        axisTick: {
          show: false
        },
        axisLine: {
          show: false
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#f3f4f6'
          }
        }
      },
      series: [{
        type: 'custom',
        renderItem: (params: any, api: any) => {
          const xValue = api.value(0)
          const minValue = api.value(1)
          const maxValue = api.value(2)
          
          // 获取坐标位置，确保与X轴刻度对齐
          const minCoord = api.coord([xValue, minValue])
          const maxCoord = api.coord([xValue, maxValue])
          
          // 计算条形图的宽度和位置
          const barWidth = 16 // 稍微减小宽度以更好地对齐
          const x = minCoord[0] - barWidth / 2
          const y = maxCoord[1]
          const height = Math.max(3, minCoord[1] - maxCoord[1]) // 确保最小高度
          
          return {
            type: 'rect',
            shape: {
              x: x,
              y: y,
              width: barWidth,
              height: height,
              r: 3 // 添加圆角
            },
            style: {
              fill: '#ef4444', // 红色
              stroke: '#ffffff',
              lineWidth: 1,
              opacity: 0.9
            }
          }
        },
        data: seriesData
      }]
    }

    setChartOption(option)
  }

  const fetchRestingHeartRateData = async () => {
    if (!userDetail?.mobile) return
    
    setChartLoading(true)
    try {
      // 计算睡眠周期：选择日期的前一天18:00到当天18:00
      const targetDate = new Date(selectedDate)
      const startTime = new Date(targetDate)
      startTime.setDate(startTime.getDate() - 1)
      startTime.setHours(18, 0, 0, 0)
      
      const endTime = new Date(targetDate)
      endTime.setHours(18, 0, 0, 0)
      
      // 获取睡眠数据和心率数据
      const [sleepResponse, heartRateResponse] = await Promise.all([
        fetch(`/api/health/query?${new URLSearchParams({
          mobile: userDetail.mobile,
          type: 'sleep',
          page: '1',
          limit: '100',
          start_date: selectedDate,
          start_time: Math.floor(startTime.getTime() / 1000).toString(),
          end_time: Math.floor(endTime.getTime() / 1000).toString()
        })}`),
        fetch(`/api/health/query?${new URLSearchParams({
          mobile: userDetail.mobile,
          type: 'heart_rate',
          page: '1',
          limit: '2000', // 获取更多心率数据
          start_date: selectedDate,
          start_time: Math.floor(startTime.getTime() / 1000).toString(),
          end_time: Math.floor(endTime.getTime() / 1000).toString()
        })}`)
      ])
      
      const sleepResult = await sleepResponse.json()
      const heartRateResult = await heartRateResponse.json()
      
      if (sleepResult.success && heartRateResult.success && 
          sleepResult.data.logs.length > 0 && heartRateResult.data.logs.length > 0) {
        calculateRestingHeartRate(sleepResult.data.logs, heartRateResult.data.logs, startTime, endTime)
      } else {
        setRestingHeartRateData([])
        setChartOption(null)
      }
    } catch (error) {
      console.error('获取静息心率数据错误:', error)
      setRestingHeartRateData([])
      setChartOption(null)
    } finally {
      setChartLoading(false)
    }
  }

  const calculateRestingHeartRate = (sleepLogs: any[], heartRateLogs: any[], startTime: Date, endTime: Date) => {
    // 1. 识别有效的睡眠周期
    const sleepPeriods: Array<{
      startTime: number
      endTime: number
      type: string
    }> = []
    
    sleepLogs.forEach((log) => {
      try {
        const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
        
        if (logData.arraySleepQuality && Array.isArray(logData.arraySleepQuality)) {
          const sleepData = logData.arraySleepQuality
          const unitLength = parseInt(logData.sleepUnitLength || '1')
          let logStartTime = parseInt(logData.startTs || log.timestamp)
          
          if (logStartTime < 10000000000) {
            logStartTime = logStartTime * 1000
          }
          
          // 只保留深度睡眠和浅睡眠期间的数据，过滤掉清醒和REM期间
          sleepData.forEach((quality: any, index: number) => {
            const qualityNum = typeof quality === 'string' ? parseInt(quality) : quality
            const dataStartTime = logStartTime + (index * unitLength * 60 * 1000)
            const dataEndTime = logStartTime + ((index + 1) * unitLength * 60 * 1000)
            
            // 只保留深度睡眠(1)和浅睡眠(2,4)期间
            if (qualityNum === 1 || qualityNum === 2 || qualityNum === 4) {
              let sleepType = ''
              switch (qualityNum) {
                case 1: sleepType = '深度睡眠'; break
                case 2: 
                case 4: sleepType = '浅睡眠'; break
              }
              
              sleepPeriods.push({
                startTime: dataStartTime,
                endTime: dataEndTime,
                type: sleepType
              })
            }
          })
        }
      } catch (e) {
        console.error('处理睡眠数据错误:', e, log)
      }
    })
    
    // 2. 采集睡眠期间的心率数据
    const sleepHeartRates: Array<{
      timestamp: number
      value: number
    }> = []
    
    heartRateLogs.forEach((log) => {
      try {
        const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
        
        if (logData.onceHeartValue) {
          const heartRate = parseInt(logData.onceHeartValue)
          const timestamp = parseInt(logData.ts || log.timestamp)
          const finalTimestamp = timestamp < 10000000000 ? timestamp * 1000 : timestamp
          
          if (!isNaN(heartRate) && heartRate > 0) {
            // 检查这个心率数据是否在有效睡眠期间
            const isInSleepPeriod = sleepPeriods.some(period => 
              finalTimestamp >= period.startTime && finalTimestamp <= period.endTime
            )
            
            if (isInSleepPeriod) {
              sleepHeartRates.push({
                timestamp: finalTimestamp,
                value: heartRate
              })
            }
          }
        }
      } catch (e) {
        console.error('处理心率数据错误:', e, log)
      }
    })
    
    // 按时间排序
    sleepHeartRates.sort((a, b) => a.timestamp - b.timestamp)
    
    // 3. 使用滑动窗口计算静息心率
    const restingHeartRates = calculateRestingHeartRateWithSlidingWindow(sleepHeartRates)
    
    setRestingHeartRateData(restingHeartRates)
    generateRestingHeartRateChart(restingHeartRates, startTime, endTime)
  }

  const calculateRestingHeartRateWithSlidingWindow = (heartRateData: Array<{timestamp: number, value: number}>) => {
    if (heartRateData.length === 0) return []
    
    const windowSizeMinutes = 30 // 30分钟窗口
    const windowSizeMs = windowSizeMinutes * 60 * 1000
    
    const results: Array<{
      date: string
      restingHeartRate: number
      windowStart: number
      windowEnd: number
      dataCount: number
    }> = []
    
    // 按小时分组处理数据，计算每小时的静息心率
    const hourlyGroups = new Map<number, Array<{timestamp: number, value: number}>>()
    
    heartRateData.forEach(data => {
      const hour = new Date(data.timestamp).getHours()
      if (!hourlyGroups.has(hour)) {
        hourlyGroups.set(hour, [])
      }
      hourlyGroups.get(hour)!.push(data)
    })
    
    // 为每个有数据的小时计算静息心率
    hourlyGroups.forEach((hourData, hour) => {
      if (hourData.length < 5) return // 数据点太少，跳过
      
      let minAvgHr = Infinity
      let bestWindow = { start: 0, end: 0, count: 0 }
      
      // 滑动窗口算法
      for (let i = 0; i < hourData.length; i++) {
        const windowStart = hourData[i].timestamp
        const windowEnd = windowStart + windowSizeMs
        
        // 收集窗口内的数据
        const windowData = hourData.filter(data => 
          data.timestamp >= windowStart && data.timestamp <= windowEnd
        )
        
        if (windowData.length >= 5) { // 至少5个数据点
          const avgHr = windowData.reduce((sum, data) => sum + data.value, 0) / windowData.length
          
          if (avgHr < minAvgHr) {
            minAvgHr = avgHr
            bestWindow = {
              start: windowStart,
              end: windowEnd,
              count: windowData.length
            }
          }
        }
      }
      
      if (minAvgHr !== Infinity) {
        results.push({
          date: new Date(bestWindow.start).toLocaleString(),
          restingHeartRate: Math.round(minAvgHr),
          windowStart: bestWindow.start,
          windowEnd: bestWindow.end,
          dataCount: bestWindow.count
        })
      }
    })
    
    return results.sort((a, b) => a.windowStart - b.windowStart)
  }

  const generateRestingHeartRateChart = (restingData: any[], startTime: Date, endTime: Date) => {
    if (restingData.length === 0) {
      setChartOption(null)
      return
    }
    
    // 生成24小时时间轴
    const timeLabels = []
    const categoryData = []
    
    for (let hour = 0; hour < 24; hour++) {
      categoryData.push(hour)
      if (hour % 2 === 0) {
        timeLabels.push(`${hour.toString().padStart(2, '0')}:00`)
      }
    }
    
    // 转换数据为ECharts格式
    const seriesData = restingData.map((data) => {
      const hour = new Date(data.windowStart).getHours()
      
      return {
        name: `${hour.toString().padStart(2, '0')}:00`,
        value: [
          hour, // X轴位置
          data.restingHeartRate, // 静息心率值
          data.dataCount, // 数据点数量
          data.windowStart, // 窗口开始时间
          data.windowEnd // 窗口结束时间
        ],
        itemStyle: {
          color: '#10b981' // 绿色表示静息心率
        }
      }
    })
    
    // 计算Y轴范围
    const heartRates = restingData.map(d => d.restingHeartRate)
    const minHr = Math.min(...heartRates)
    const maxHr = Math.max(...heartRates)
    const range = maxHr - minHr
    const buffer = Math.max(3, Math.ceil(range * 0.1))
    const yAxisMin = Math.max(0, minHr - buffer)
    const yAxisMax = maxHr + buffer

    const option = {
      title: {
        text: '静息心率分析',
        left: 'center',
        textStyle: {
          fontSize: 16,
          color: '#374151'
        }
      },
      tooltip: {
        formatter: (params: any) => {
          const data = params.data
          const hour = data.value[0]
          const rhr = data.value[1]
          const count = data.value[2]
          const startTime = new Date(data.value[3])
          const endTime = new Date(data.value[4])
          
          return `
            <div>
              <strong>${hour.toString().padStart(2, '0')}:00 时段</strong><br/>
              静息心率: ${rhr} 次/分<br/>
              数据点数: ${count}个<br/>
              最佳窗口: ${startTime.toLocaleTimeString()} - ${endTime.toLocaleTimeString()}
            </div>
          `
        }
      },
      grid: {
        left: '10%',
        right: '10%',
        top: '15%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: categoryData,
        axisLabel: {
          fontSize: 12,
          color: '#6b7280',
          formatter: (value: number) => {
            if (value % 2 === 0) {
              return `${value.toString().padStart(2, '0')}:00`
            }
            return ''
          },
          interval: 0
        },
        axisTick: {
          show: true,
          alignWithLabel: true
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#e5e7eb'
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#f3f4f6',
            type: 'dashed'
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '静息心率 (次/分)',
        min: yAxisMin,
        max: yAxisMax,
        nameTextStyle: {
          color: '#6b7280',
          fontSize: 12
        },
        axisLabel: {
          fontSize: 12,
          color: '#6b7280'
        },
        axisTick: {
          show: false
        },
        axisLine: {
          show: false
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#f3f4f6'
          }
        }
      },
      series: [{
        type: 'scatter',
        symbolSize: 8,
        data: seriesData,
        itemStyle: {
          color: '#10b981',
          borderColor: '#ffffff',
          borderWidth: 2
        }
      }]
    }

    setChartOption(option)
  }

  const formatTime = (timeString: string) => {
    try {
      // 尝试多种时间格式解析
      let date: Date
      
      // 如果是纯数字字符串，可能是时间戳（秒或毫秒）
      if (/^\d+$/.test(timeString)) {
        const timestamp = parseInt(timeString)
        // 判断是秒还是毫秒时间戳
        date = timestamp > 1000000000000 ? new Date(timestamp) : new Date(timestamp * 1000)
      } else {
        // 尝试直接解析
        date = new Date(timeString)
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return timeString
      }
      
      return date.toLocaleString('zh-CN')
    } catch (e) {
      return timeString
    }
  }

  const getGenderText = (gender: number) => {
    switch (gender) {
      case 1: return '男'
      case 2: return '女'
      default: return '未知'
    }
  }

  const getGenderColor = (gender: number) => {
    switch (gender) {
      case 1: return 'bg-blue-100 text-blue-800'
      case 2: return 'bg-pink-100 text-pink-800'
      default: return 'bg-gray-100 text-gray-800'
    }
  }

  const getUserInitials = (name: string) => {
    if (!name) return 'U'
    return name.length > 1 ? name.substring(0, 2) : name[0]
  }

  const formatHealthData = (type: string, data: any) => {
    try {
      const logData = typeof data === 'string' ? JSON.parse(data) : data
      switch (type) {
        case 'heart_rate':
          return `${logData.onceHeartValue || logData.heart_rate || logData.value || '--'} bpm`
        case 'temperature':
          return `${logData.temperature || logData.value || '--'} °C`
        case 'spo':
        case 'spo2':
          const bloodOxygen = logData.Blood_oxygen || logData.spo2 || logData.value || '--'
          const isAuto = logData.isAutoMeasure !== undefined ? (logData.isAutoMeasure ? '自动' : '手动') : ''
          return `${bloodOxygen}% ${isAuto ? `(${isAuto})` : ''}`
        case 'hrv':
          return `${logData.hrv || logData.value || '--'} ms`
        case 'sleep':
          if (logData.arraySleepQuality && Array.isArray(logData.arraySleepQuality)) {
            const sleepData = logData.arraySleepQuality
            const unitLength = parseInt(logData.sleepUnitLength || '1')
            
            // 统计各阶段时长（分钟）
            const deepSleep = sleepData.filter((q: string) => q === '1').length * unitLength
            const lightSleep = sleepData.filter((q: string) => q === '2').length * unitLength
            const remSleep = sleepData.filter((q: string) => q === '3').length * unitLength
            const awake = sleepData.filter((q: string) => q === '5').length * unitLength
            const totalSleep = deepSleep + lightSleep + remSleep
            
            return `总睡眠${Math.round(totalSleep/60*10)/10}h (深睡${deepSleep}min, 浅睡${lightSleep}min, REM${remSleep}min, 清醒${awake}min)`
          }
          return `${logData.duration || logData.value || '--'} 小时`
        case 'step':
        case 'steps':
          const totalSteps = logData.detailMinterStep || logData.steps || logData.value || '--'
          const calories = logData.calories ? `${logData.calories}卡` : ''
          const distance = logData.distance ? `${logData.distance}km` : ''
          const extras = [calories, distance].filter(Boolean).join(', ')
          return `${totalSteps}步 ${extras ? `(${extras})` : ''}`
        default:
          return JSON.stringify(logData).substring(0, 50) + '...'
      }
    } catch (e) {
      return typeof data === 'string' ? data.substring(0, 50) + '...' : JSON.stringify(data).substring(0, 50) + '...'
    }
  }

  if (loading) {
    return (
      <div className="p-6">
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-2 text-gray-500">加载用户详情中...</p>
          </div>
        </div>
      </div>
    )
  }

  if (!userDetail) {
    return (
      <div className="p-6">
        <div className="text-center py-12">
          <User className="w-12 h-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">用户不存在</h3>
          <p className="text-gray-500 mb-4">未找到该用户的详细信息</p>
          <Button onClick={onBack}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面标题和返回按钮 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button variant="outline" onClick={onBack}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回用户列表
          </Button>
          <div>
            <h1 className="text-2xl font-semibold text-gray-900">用户详情</h1>
            <p className="text-sm text-gray-500 mt-1">查看用户的详细信息和健康数据</p>
          </div>
        </div>
      </div>

      {/* 用户基本信息 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <Card className="lg:col-span-1">
          <CardHeader>
            <CardTitle className="flex items-center">
              <User className="w-5 h-5 mr-2" />
              基本信息
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 头像和姓名 */}
            <div className="text-center">
              <Avatar className="w-20 h-20 mx-auto mb-4">
                <AvatarImage src={userDetail.avatar} alt={userDetail.name} />
                <AvatarFallback className="bg-blue-100 text-blue-600 text-xl">
                  {getUserInitials(userDetail.name)}
                </AvatarFallback>
              </Avatar>
              <h3 className="text-lg font-semibold text-gray-900">{userDetail.name || '未设置姓名'}</h3>
              <p className="text-sm text-gray-500">ID: {userDetail.id}</p>
            </div>

            {/* 详细信息 */}
            <div className="space-y-4">
              <div className="flex items-center space-x-3">
                <Phone className="w-4 h-4 text-gray-400" />
                <div>
                  <p className="text-sm text-gray-500">手机号</p>
                  <p className="font-medium">
                    {userDetail.mobile ? `+${userDetail.cc || 86} ${userDetail.mobile}` : '未绑定'}
                  </p>
                </div>
              </div>

              <div className="flex items-center space-x-3">
                <User className="w-4 h-4 text-gray-400" />
                <div>
                  <p className="text-sm text-gray-500">性别</p>
                  <Badge className={getGenderColor(userDetail.gender)}>
                    {getGenderText(userDetail.gender)}
                  </Badge>
                </div>
              </div>

              <div className="flex items-center space-x-3">
                <Calendar className="w-4 h-4 text-gray-400" />
                <div>
                  <p className="text-sm text-gray-500">年龄</p>
                  <p className="font-medium">
                    {userDetail.age > 0 ? `${userDetail.age} 岁` : '未设置'}
                  </p>
                </div>
              </div>

              {userDetail.height && parseFloat(userDetail.height) > 0 && (
                <div className="flex items-center space-x-3">
                  <Ruler className="w-4 h-4 text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-500">身高</p>
                    <p className="font-medium">{userDetail.height} cm</p>
                  </div>
                </div>
              )}

              {userDetail.weight && parseFloat(userDetail.weight) > 0 && (
                <div className="flex items-center space-x-3">
                  <Weight className="w-4 h-4 text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-500">体重</p>
                    <p className="font-medium">{userDetail.weight} kg</p>
                  </div>
                </div>
              )}

              {/* BMI计算 */}
              {userDetail.height && userDetail.weight && 
               parseFloat(userDetail.height) > 0 && parseFloat(userDetail.weight) > 0 && (() => {
                 const heightInM = parseFloat(userDetail.height) / 100
                 const weight = parseFloat(userDetail.weight)
                 const bmi = weight / (heightInM * heightInM)
                 
                 let bmiStatus = '正常'
                 let bmiColor = 'bg-green-100 text-green-800'
                 
                 if (bmi < 18.5) {
                   bmiStatus = '偏瘦'
                   bmiColor = 'bg-blue-100 text-blue-800'
                 } else if (bmi >= 24 && bmi < 28) {
                   bmiStatus = '超重'
                   bmiColor = 'bg-yellow-100 text-yellow-800'
                 } else if (bmi >= 28) {
                   bmiStatus = '肥胖'
                   bmiColor = 'bg-red-100 text-red-800'
                 }
                 
                 return (
                   <div className="flex items-center space-x-3">
                     <Activity className="w-4 h-4 text-gray-400" />
                     <div>
                       <p className="text-sm text-gray-500">BMI</p>
                       <div className="flex items-center space-x-2">
                         <p className="font-medium">{bmi.toFixed(1)}</p>
                         <Badge className={bmiColor}>
                           {bmiStatus}
                         </Badge>
                       </div>
                     </div>
                   </div>
                 )
               })()}

              {userDetail.city && (
                <div className="flex items-center space-x-3">
                  <MapPin className="w-4 h-4 text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-500">城市</p>
                    <p className="font-medium">{userDetail.city}</p>
                  </div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 健康数据统计 */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle className="flex items-center">
              <Activity className="w-5 h-5 mr-2" />
              健康数据概览
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
              <div className="text-center p-4 bg-blue-50 rounded-lg">
                <Database className="w-8 h-8 text-blue-600 mx-auto mb-2" />
                <p className="text-2xl font-bold text-blue-600">{userDetail.totalHealthLogs.toLocaleString()}</p>
                <p className="text-sm text-gray-600">总记录数</p>
              </div>
              {userDetail.healthStats.slice(0, 3).map((stat, index) => (
                <div key={stat.type} className="text-center p-4 bg-gray-50 rounded-lg">
                  <Activity className="w-8 h-8 text-gray-600 mx-auto mb-2" />
                  <p className="text-2xl font-bold text-gray-900">{stat.count.toLocaleString()}</p>
                  <p className="text-sm text-gray-600">{stat.type}</p>
                </div>
              ))}
            </div>

            {/* 健康数据类型分布图表 */}
            {userDetail.healthStats.length > 0 && (
              <div className="h-64">
                <ReactECharts
                  option={{
                    tooltip: {
                      trigger: 'axis',
                      axisPointer: {
                        type: 'shadow'
                      }
                    },
                    grid: {
                      left: '3%',
                      right: '4%',
                      bottom: '3%',
                      containLabel: true
                    },
                    xAxis: {
                      type: 'category',
                      data: userDetail.healthStats.map(stat => stat.type),
                      axisLabel: {
                        rotate: 45
                      }
                    },
                    yAxis: {
                      type: 'value'
                    },
                    series: [{
                      name: '记录数量',
                      type: 'bar',
                      data: userDetail.healthStats.map(stat => stat.count),
                      itemStyle: {
                        color: '#3b82f6'
                      }
                    }]
                  }}
                  style={{ height: '100%', width: '100%' }}
                />
              </div>
            )}

            <div className="mt-6 flex justify-center">
              <Button 
                variant="outline" 
                onClick={() => window.open(`/health-query?mobile=${userDetail.mobile}`, '_blank')}
              >
                查看更多健康记录
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 健康数据图表分析 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Moon className="w-5 h-5 mr-2" />
            健康数据图表分析
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* 筛选器 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <Label htmlFor="date-select">选择日期</Label>
              <Input
                id="date-select"
                type="date"
                value={selectedDate}
                onChange={(e) => setSelectedDate(e.target.value)}
                className="mt-1"
              />
            </div>
            <div>
              <Label htmlFor="type-select">数据类型</Label>
              <Select value={selectedDataType} onValueChange={setSelectedDataType}>
                <SelectTrigger className="mt-1">
                  <SelectValue placeholder="选择数据类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="sleep">睡眠数据</SelectItem>
                  <SelectItem value="heart_rate">心率数据</SelectItem>
                  <SelectItem value="spo">血氧数据</SelectItem>
                  <SelectItem value="steps">步数数据</SelectItem>
                  <SelectItem value="hrv">HRV数据</SelectItem>
                  <SelectItem value="temperature">皮肤温度</SelectItem>
                  <SelectItem value="activity">活动分析</SelectItem>
                  <SelectItem value="energy">能量消耗</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="flex items-end">
              <Button 
                onClick={() => {
                  if (selectedDataType === 'sleep') {
                    fetchSleepData()
                  } else if (selectedDataType === 'heart_rate') {
                    fetchHeartRateData()
                  } else if (selectedDataType === 'steps') {
                    // 步数数据由StepChart组件内部处理，这里不需要额外操作
                    console.log('选择了步数数据类型')
                  } else if (selectedDataType === 'hrv') {
                    // HRV数据由HRVChart组件内部处理，这里不需要额外操作
                    console.log('选择了HRV数据类型')
                  } else if (selectedDataType === 'temperature') {
                    // 温度数据由TemperatureChart组件内部处理，这里不需要额外操作
                    console.log('选择了温度数据类型')
                  } else if (selectedDataType === 'activity') {
                    // 活动分析数据由ActivityAnalysisChart组件内部处理，这里不需要额外操作
                    console.log('选择了活动分析数据类型')
                  } else if (selectedDataType === 'energy') {
                    // 能量消耗数据由EnergyConsumptionChart组件内部处理，这里不需要额外操作
                    console.log('选择了能量消耗数据类型')
                  }
                }}
                disabled={chartLoading}
                className="w-full"
              >
                <Filter className="w-4 h-4 mr-2" />
                {chartLoading ? '加载中...' : '更新图表'}
              </Button>
            </div>
          </div>

          {/* 心率图表 - 使用新的心率图表组件 */}
          {selectedDataType === 'heart_rate' && (
            <HeartRateChart 
              userId={userDetail.id?.toString() || userDetail.mobile}
              selectedDate={selectedDate}
            />
          )}

          {/* 睡眠图表 */}
          {selectedDataType === 'sleep' && (
            <div className="space-y-4">
              <div className="text-sm text-gray-600">
                睡眠周期：{selectedDate ? `${new Date(new Date(selectedDate).getTime() - 24*60*60*1000).toLocaleDateString()} 18:00 - ${new Date(selectedDate).toLocaleDateString()} 18:00` : '请选择日期'}
              </div>
              
              {chartLoading ? (
                <div className="flex items-center justify-center h-64">
                  <div className="text-center">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
                    <p className="mt-2 text-gray-500">加载睡眠数据中...</p>
                  </div>
                </div>
              ) : sleepChartData && sleepChartData.length > 0 && chartOption ? (
                <div className="space-y-4">
                  {/* ECharts 睡眠图表 */}
                  <div className="h-96 border rounded bg-white">
                    <ReactECharts
                      option={chartOption}
                      style={{ height: '100%', width: '100%' }}
                      opts={{ renderer: 'canvas' }}
                    />
                  </div>
                  
                  {/* 统计信息 */}
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                    {['深度睡眠', '浅睡眠', 'REM睡眠', '清醒'].map(type => {
                      const segments = sleepChartData.filter((seg: any) => seg.type === type)
                      const totalDuration = segments.reduce((sum: number, seg: any) => sum + seg.duration, 0)
                      const color = type === '深度睡眠' ? '#1e40af' : 
                                   type === '浅睡眠' ? '#3b82f6' : 
                                   type === 'REM睡眠' ? '#8b5cf6' : '#ef4444'
                      
                      return segments.length > 0 ? (
                        <div key={type} className="text-center p-3 bg-gray-50 rounded">
                          <div className="flex items-center justify-center mb-2">
                            <div 
                              className="w-4 h-4 rounded mr-2" 
                              style={{ backgroundColor: color }}
                            ></div>
                            <span className="font-medium">{type}</span>
                          </div>
                          <div className="text-xs text-gray-600">
                            {segments.length}段 · {totalDuration}分钟
                          </div>
                          <div className="text-xs text-gray-500">
                            {Math.round(totalDuration / 60 * 10) / 10}小时
                          </div>
                        </div>
                      ) : null
                    })}
                  </div>
                </div>
              ) : (
                <div className="text-center py-12">
                  <Moon className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                  <h3 className="text-lg font-medium text-gray-900 mb-2">暂无睡眠数据</h3>
                  <p className="text-gray-500">选择的日期没有找到睡眠记录</p>
                </div>
              )}

              {/* 睡眠图例 */}
              {sleepChartData.length > 0 && (
                <div className="flex justify-center space-x-6 text-sm">
                  <div className="flex items-center">
                    <div className="w-4 h-4 bg-blue-800 mr-2"></div>
                    <span>深度睡眠</span>
                  </div>
                  <div className="flex items-center">
                    <div className="w-4 h-4 bg-blue-500 mr-2"></div>
                    <span>浅睡眠</span>
                  </div>
                  <div className="flex items-center">
                    <div className="w-4 h-4 bg-purple-500 mr-2"></div>
                    <span>REM睡眠</span>
                  </div>
                  <div className="flex items-center">
                    <div className="w-4 h-4 bg-red-500 mr-2"></div>
                    <span>清醒</span>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* 步数图表 */}
          {selectedDataType === 'steps' && (
            <StepChart 
              userId={userDetail.id?.toString() || userDetail.mobile}
              selectedDate={selectedDate}
            />
          )}

          {/* HRV图表 */}
          {selectedDataType === 'hrv' && (
            <HRVChart 
              userId={userDetail.id?.toString() || userDetail.mobile}
              selectedDate={selectedDate}
            />
          )}

          {/* 温度图表 */}
          {selectedDataType === 'temperature' && (
            <TemperatureChart 
              userId={userDetail.id?.toString() || userDetail.mobile}
              selectedDate={selectedDate}
            />
          )}

          {/* 活动分析图表 */}
          {selectedDataType === 'activity' && (
            <ActivityAnalysisChart 
              userId={userDetail.id?.toString() || userDetail.mobile}
              selectedDate={selectedDate}
            />
          )}

          {/* 能量消耗图表 */}
          {selectedDataType === 'energy' && (
            <EnergyConsumptionChart 
              userId={userDetail.id?.toString() || userDetail.mobile}
              selectedDate={selectedDate}
            />
          )}
        </CardContent>
      </Card>

      {/* 最近健康记录 */}
      {userDetail.recentHealthLogs && userDetail.recentHealthLogs.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Clock className="w-5 h-5 mr-2" />
              最近健康记录
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b">
                    <th className="text-left p-3">记录ID</th>
                    <th className="text-left p-3">数据类型</th>
                    <th className="text-left p-3">设备ID</th>
                    <th className="text-left p-3">数据内容</th>
                    <th className="text-left p-3">记录时间</th>
                  </tr>
                </thead>
                <tbody>
                  {userDetail.recentHealthLogs.map((log) => (
                    <tr key={log.id} className="border-b hover:bg-gray-50">
                      <td className="p-3 font-mono text-xs">{log.id}</td>
                      <td className="p-3">
                        <Badge className="bg-blue-100 text-blue-800">
                          {log.type}
                        </Badge>
                      </td>
                      <td className="p-3 font-mono text-xs">{log.device_id}</td>
                      <td className="p-3 max-w-xs">
                        <div className="text-xs">
                          {formatHealthData(log.type, log.data)}
                        </div>
                      </td>
                      <td className="p-3 text-xs text-gray-500">
                        {formatTime(log.created_at)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            
            <div className="mt-4 flex justify-center">
              <Button 
                variant="outline" 
                onClick={() => window.open(`/health-query?mobile=${userDetail.mobile}`, '_blank')}
              >
                查看更多健康记录
              </Button>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}